package cn.kaguyaever.web;

import cn.kaguyaever.entity.*;
import cn.kaguyaever.service.CandidateService;
import cn.kaguyaever.service.JudgeService;
import cn.kaguyaever.service.ProjectService;
import cn.kaguyaever.service.VoteService;
import cn.kaguyaever.service.impl.CandidateServiceImpl;
import cn.kaguyaever.service.impl.JudgeServiceImpl;
import cn.kaguyaever.service.impl.ProjectServiceImpl;
import cn.kaguyaever.service.impl.VoteServiceImpl;
import cn.kaguyaever.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/voteServlet")
public class VoteServlet extends BaseServlet {

    private VoteService voteService = new VoteServiceImpl();

    private CandidateService candidateService = new CandidateServiceImpl();

    private JudgeService judgeService = new JudgeServiceImpl();

    private ProjectService projectService = new ProjectServiceImpl();

    protected void createVote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User loginUser = (User) req.getSession().getAttribute("user");
        Integer userId = loginUser.getId();
        String voteId = System.currentTimeMillis()+""+userId;
        String title = req.getParameter("title");
        String[] candidate = req.getParameterValues("candidate");
        Project project = (Project)req.getSession().getAttribute("project");
        Vote vote = new Vote(voteId,title,project.getProjectId(),null,0,project.getCount()+1);
        voteService.createVote(vote);
        projectService.setCount(vote.getNum(),project.getProjectId());
        project.setCount(project.getCount()+1);
        for(String s:candidate){
            candidateService.createCandidate(new Candidate(null,s,0,voteId));
        }
        if(req.getSession().getAttribute("voteId")==null){
            req.getSession().setAttribute("voteId",voteId);
        }
        List<Vote> votes = voteService.queryAllVote(project.getProjectId());
        for(Vote entry:votes){
            if(entry.getVoteStatus()==0||entry.getVoteStatus()==1){
                req.getSession().setAttribute("voteId",entry.getVoteId());
                break;
            }
        }
        req.getSession().setAttribute("project",project);
        req.getSession().setAttribute("votes",votes);
        resp.sendRedirect("user/home.jsp");
    }

    protected void chooseJudge(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String projectId = ((Project)req.getSession().getAttribute("project")).getProjectId();
        List<Judge> judges = judgeService.queryJudge(projectId);
        req.getSession().setAttribute("judges",judges);
        resp.sendRedirect("user/choose_judge.jsp");
    }

    protected void beginVote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String voteId = (String)req.getSession().getAttribute("voteId");
        String[] judges = req.getParameterValues("judges");
        if(judges==null){
            req.setAttribute("msg", "至少选择一个评委！");
            req.getRequestDispatcher("/user/choose_judge.jsp").forward(req, resp);
        }else {
            for (String judgeId : judges) {
                judgeService.setStatus(Integer.parseInt(judgeId));
            }
            voteService.beginVote(voteId);
            List<Vote> votes = voteService.queryAllVote(((Project)req.getSession().getAttribute("project")).getProjectId());
            req.getSession().setAttribute("votes",votes);
            req.getSession().setAttribute("voting",voteService.queryVote(voteId));
            resp.sendRedirect("user/home.jsp");
        }
    }

    protected void endVote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Project project = (Project)req.getSession().getAttribute("project");
        String projectId = project.getProjectId();
        String voteId = (String) req.getSession().getAttribute("voteId");
        judgeService.clearStatus(projectId);
        voteService.endVote(voteId);
        List<Candidate> candidates = candidateService.queryCandidate(voteId);
        Integer maxCount = 0;
        StringBuffer winner = new StringBuffer();
        for(Candidate candidate:candidates){
            if(candidate.getCount()>maxCount){
                maxCount = candidate.getCount();
                winner.delete(0,winner.length());
                winner.append(candidate.getName());
            }else if(candidate.getCount().equals(maxCount)){
                winner.append("、");
                winner.append(candidate.getName());
            }
        }
        voteService.setWinner(winner.toString(),voteId);
        List<Vote> votes = voteService.queryAllVote(projectId);
        for(Vote vote:votes){
            if(vote.getVoteStatus()==0||vote.getVoteStatus()==1){
                req.getSession().setAttribute("voteId",vote.getVoteId());
                break;
            }
        }
        req.getSession().setAttribute("votes",votes);
        resp.sendRedirect("user/home.jsp");
    }

    protected void castVote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String candidate = req.getParameter("candidateId");
        if(candidate==null){
            req.getSession().setAttribute("msg","请选择一个选项！");
            req.getRequestDispatcher("/judge/vote.jsp").forward(req,resp);
        }else {
            Integer candidateId = Integer.parseInt(candidate);
            Judge judge = (Judge) req.getSession().getAttribute("judge");
            candidateService.voteCandidate(candidateId);
            judgeService.votedJudge(judge.getJudgeId());
            judge.setStatus(1);
            req.getSession().setAttribute("judge", judge);
            req.getSession().setAttribute("msg", "投票成功");
            resp.sendRedirect("judge/vote.jsp");
        }
    }

    protected void giveUp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Judge judge = (Judge)req.getSession().getAttribute("judge");
        judgeService.votedJudge(judge.getJudgeId());
        judge.setStatus(1);
        req.getSession().setAttribute("judge", judge);
        req.getSession().setAttribute("msg", "弃权成功");
        resp.sendRedirect("judge/vote.jsp");
    }

    protected void queryCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       Vote vote = (Vote)req.getSession().getAttribute("voting");
       Gson gson = new Gson();
       if(vote!=null) {
           List<Candidate> candidates = candidateService.queryCandidate(vote.getVoteId());
           String candidateList = gson.toJson(candidates);
           resp.getWriter().write(candidateList);
       }else {
           String tmp = gson.toJson(null);
           resp.getWriter().write(tmp);
       }
    }
}
